package jh.view;

import java.text.SimpleDateFormat;


import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jh.ios.forecast.R;

/**
 *
 * @author 自定义listview实现上拉刷新和下拉加载
 * 2018-08-25 刘明昆 q571039838
 *
 */
public class MyListView extends ListView implements AbsListView.OnScrollListener{

    private View bottomview; //尾文件
    private int totaItemCounts;//用于表示是下拉还是上拉
    private int lassVisible; //上拉
    private LoadListener loadListener; //接口回调
    private int bottomHeight;//尾文件高度
    private int Yload;//位置
    boolean isLoading;//加载状态

    public MyListView(Context context) {
        super(context);
        Init(context);
    }

    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        Init(context);
    }

    public MyListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        Init(context);
    }

    private void Init(Context context) {

        //拿到尾布局文件
        bottomview=LinearLayout.inflate(context, R.layout.layout_list_bottom, null);
        //测量尾文件高度
        bottomview.measure(0,0);
        //拿到高度
        bottomHeight=bottomview.getMeasuredHeight();
        //隐藏view
        bottomview.setPadding(0, -bottomHeight, 0, 0);

        this.addFooterView(bottomview);

        //设置拉动监听
        this.setOnScrollListener(this);

    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Yload=(int) ev.getY();
                break;

            case MotionEvent.ACTION_MOVE:

                break;
        }
        return super.onTouchEvent(ev);
    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if(totaItemCounts==lassVisible&&scrollState==SCROLL_STATE_IDLE){
            if(!isLoading){
                isLoading=true;
                bottomview.setPadding(0, 0, 0, 0);
                //加载数据
                loadListener.onLoad();
            }
        }
    }


    //接口回调
    public interface LoadListener{
        void onLoad();
    }


    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {

        this.lassVisible=firstVisibleItem+visibleItemCount;
        this.totaItemCounts=totalItemCount;
    }
    //加载完成
    public void loadComplete(){
        isLoading=false;
        bottomview.setPadding(0, -bottomHeight, 0, 0);
    }

    public void setInteface(LoadListener loadListener){
        this.loadListener=loadListener;
    }

}